package main

import (
	"fmt"
	"io"
	"net/http"
	"plugin"
)

var call func() string

func Call(w http.ResponseWriter, r *http.Request) {
	if call != nil {
		io.WriteString(w, call()+"\n")
	}
}

func Reload(w http.ResponseWriter, r *http.Request) {
	v := r.FormValue("v")
	if v == "" {
		io.WriteString(w, "missing version\n")
		return
	}
	name := "plugin." + v + ".so"
	p, err := plugin.Open(name)
	if err != nil {
		io.WriteString(w, fmt.Sprintf("open %s failed|err:%v\n", name, err))
		return
	}

	f, err := p.Lookup("Version")
	if err != nil {
		io.WriteString(w, fmt.Sprintf("lookup %s failed|err:%v\n", name, err))
		return
	}

	var ok bool
	call, ok = f.(func() string)
	if !ok {
		io.WriteString(w, "convert func error\n")
		return
	}
	io.WriteString(w, "reload "+v+" success\n")
}

func main() {
	http.HandleFunc("/call", Call)
	http.HandleFunc("/reload", Reload)
	http.ListenAndServe(":12311", nil)
}
